from rest_framework import serializers

from goods.models import SKU


class CartVIewSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='sku_id', required=True, min_value=1)
    count = serializers.IntegerField(label='数量', required=True, min_value=1)
    selected = serializers.BooleanField(label='是否勾选', required=False, default=True)

    def validate(self, attrs):
        # 判断商品存不存在
        sku_id = attrs.get('sku_id')

        try:
            myl_sku_id = SKU.objects.get(pk=sku_id)

        except SKU.DoseNotExist:
            serializers.ValidationError('商品不存在')

        count = attrs.get('count')

        if myl_sku_id.stock < count:
            serializers.ValidationError('库存不足')

        return attrs
